package com.cogwheel.framework.graphics;

import javax.media.opengl.GL2;
import com.cogwheel.framework.init.CPreferences;
import com.cogwheel.framework.util.*;
import com.cogwheel.framework.util.input.CKeyboard;
import com.cogwheel.framework.util.input.CMouse;

public class CSprite {
	public String TextureID;
	public float Rotation = 0.0f;
	public CRectangle Dimensions;
	public java.awt.Color Color = java.awt.Color.WHITE;
	public float x, y, xa, ya, w, h;
	protected CPreferences Preferences;
	
	
	public CSprite(CPreferences preferences, String spriteID, CRectangle dimensions){ TextureID = spriteID; Dimensions = dimensions; Preferences = preferences;}
	public void CUpdate(CMouse mouse, CKeyboard keyboard){}
	public void CSetAlpha(int alpha){ this.Color = new java.awt.Color(Color.getRed(), Color.getGreen(), Color.getBlue(), alpha); }
	public void CDraw(GL2 gl){
		//gl.glLoadIdentity();
		CBindTexture(gl);
		CToOrtho();
		CDraw2D(gl);
	}
	
	/*TODO: COMPLETE REWRITE WITH VAO/VBO!!!*/
	protected void CDraw2D(GL2 gl){
	if (TextureID != "NULL" && TextureID != null){	
			gl.glPushMatrix();
				gl.glTranslatef(xa, ya, 1f);
				gl.glRotatef(Rotation, 0f, 0f, 1f);
								
				gl.glColor4f((float)Color.getRed()/255, (float)Color.getGreen()/255, (float)Color.getBlue()/255, (float)Color.getAlpha()/255);
					gl.glBegin(GL2.GL_QUADS);
						gl.glTexCoord2f(0.0f, 1.0f); //Upper left
						gl.glVertex2f(-w, h);	
						gl.glTexCoord2f(1.0f, 1.0f); //Upper right
						gl.glVertex2f(w, h);
						gl.glTexCoord2f(1.0f, 0.0f); //Bottom right
						gl.glVertex2f(w, -h);	
						gl.glTexCoord2f(0.0f, 0.0f); //Bottom left
						gl.glVertex2f(-w, -h);
					gl.glEnd();
				gl.glColor3f(1f, 1f, 1f);
			gl.glPopMatrix();
		}
	}
	
	protected void CBindTexture(GL2 gl){
		if (TextureID != CUtils.CurrentTexture){
			if (TextureID != null){
				CAssets.CWGGetTexture(TextureID).enable(gl);
				CAssets.CWGGetTexture(TextureID).bind(gl);
			}
			CUtils.CurrentTexture = TextureID;
		}
	}
	
	/** SHOULD NOT BE CALLED AT EVERY UPDATE!
	 *  This section needs a complete rewrite
	 */
	protected void CToOrtho(){
		if (Dimensions.x != 0){ x = Preferences.WINDOW_SIZE.width/Dimensions.x;
			xa = 2 / x - 1f;
		}else{ xa = -1f; }
		
		if (Dimensions.y != 0){ y = Preferences.WINDOW_SIZE.height/Dimensions.y;
			ya = (2 / y - 1f) * -1;
		}else{ ya = 1f; }
		
		w = Dimensions.width / (float)Preferences.WINDOW_SIZE.width;
		h = Dimensions.height / (float)Preferences.WINDOW_SIZE.height;
	}
}
